package com.example.myapplication.tack_30;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.myapplication.R;
import com.example.myapplication.tack_30.adapter.CategroyAdapter;
import com.example.myapplication.tack_30.adapter.CommentAdapter;
import com.example.myapplication.tack_30.adapter.ProductAdapter;
import com.example.myapplication.tack_30.data.CategoryData;
import com.example.myapplication.tack_30.data.CollectData;
import com.example.myapplication.tack_30.data.CommentData;
import com.example.myapplication.tack_30.data.NearData;
import com.example.myapplication.tack_30.data.ProductData;
import com.example.myapplication.tack_30.data.UserCollectData;
import com.example.myapplication.utils.Common;
import com.example.myapplication.utils.OkHttpTool;
import com.example.myapplication.utils.StateData;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class Details02Activity extends AppCompatActivity {
    private ImageView exit;
    private Intent intent;
    private Gson gson;
    private NearData.RowsDTO rowsDTO;
    private TextView name;
    private TextView name1;
    private TextView total_price;
    private ImageView imgUrl;
    private TextView score;
    private TextView saleQuantity;
    private TextView avgCost;
    private List<String> listTab;
    private TabLayout tab;
    private RecyclerView category;
    private RecyclerView product;
    private JSONObject jsonObject1;
    private ImageView sc;
    private CollectData colData;
    private float totalPrice = 0;
    private TextView settlement;
    private ProductData productData;
    private RecyclerView comment;
    private LinearLayout line1;
    private LinearLayout line2;
    private ImageView imgUrl2;
    private TextView name2;
    private TextView address2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tack_30_activity_details02);
        init();
        initCheck();
        initExit();
        getCategory();
        initSC();
        getTab();
        getProduct();
        initSettlement();
    }

    private void initSettlement() {
        settlement.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(totalPrice!=0){
                    Intent intent = new Intent(Details02Activity.this,ConfirmActivity.class);
                    for (ProductData.DataDTO datum : productData.getData()) {
                        datum.setSellerId(rowsDTO.getId());
                        datum.setStoreName(rowsDTO.getName());
                    }
                    String s = gson.toJson(productData);
                    intent.putExtra(Common.COMMON,s);
                    Details02Activity.this.startActivity(intent);
//                    Details02Activity.this.finish();

                }else{
                    Toast.makeText(Details02Activity.this,"你还未点餐",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void getProduct() {
        String url = "prod-api/api/takeout/product/list?sellerId=1&categoryId=19";
        OkHttpTool.doNetRequest(url, OkHttpTool.GET, ProductData.class, new OkHttpTool.NetCallback() {
            @Override
            public void onSuccess(Object obj) {
                productData = (ProductData)obj;
                if(productData.getCode() == 200){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            product.setLayoutManager(new LinearLayoutManager(Details02Activity.this));
                            product.setAdapter(new ProductAdapter(productData.getData(), Details02Activity.this, new ProductAdapter.OnAdd() {
                                @Override
                                public void clickAdd(float price) {
                                    totalPrice += price;
                                    total_price.setText("￥"+String.valueOf(totalPrice));

                                }

                                @Override
                                public void clickMinus(float price) {
                                    totalPrice-= price;
                                    total_price.setText("￥"+String.valueOf(totalPrice));
                                }
                            }) );
                        }
                    });
                }
            }

            @Override
            public void onFailure(String msg) {

            }
        });
    }

    private void initCheck() {
        String url = "prod-api/api/takeout/collect/check?sellerId="+rowsDTO.getId();
        OkHttpTool.doNetRequest(url, OkHttpTool.GET, CollectData.class, new OkHttpTool.NetCallback() {
            @Override
            public void onSuccess(Object obj) {
                colData = (CollectData)obj;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(colData.isIsCollect()){
                            Glide.with(Details02Activity.this).load(R.drawable.ax).into(sc);
                        }else{
                            Glide.with(Details02Activity.this).load(R.drawable.sc).into(sc);
                        }
                    }
                });

            }

            @Override
            public void onFailure(String msg) {

            }
        });
    }

    private void initSC() {
        sc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    jsonObject1.put("sellerId",String.valueOf(rowsDTO.getId()));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String json = jsonObject1.toString();
                if(colData.isIsCollect()){
                    String url = "prod-api/api/takeout/collect/"+colData.getId();
                    OkHttpTool.doNetRequest(url, OkHttpTool.DELETE, StateData.class, new OkHttpTool.NetCallback() {
                        @Override
                        public void onSuccess(Object obj) {
                            StateData stateData = (StateData)obj;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if(stateData.getCode() == 200){
                                        Toast.makeText(Details02Activity.this,stateData.getMsg(),Toast.LENGTH_SHORT).show();
                                        initCheck();
                                    }
                                }
                            });

                        }

                        @Override
                        public void onFailure(String msg) {

                        }
                    });
                }else{
                    String url = "prod-api/api/takeout/collect";
                    OkHttpTool.doNetRequest(url, OkHttpTool.POST, StateData.class, new OkHttpTool.NetCallback() {
                        @Override
                        public void onSuccess(Object obj) {
                            StateData stateData = (StateData)obj;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {

                                    if(stateData.getCode() == 200){
                                        Toast.makeText(Details02Activity.this,stateData.getMsg(),Toast.LENGTH_SHORT).show();
                                        initCheck();
                                    }
                                }
                            });

                        }

                        @Override
                        public void onFailure(String msg) {

                        }
                    },json);
                }


            }
        });
    }


    private void getCategory() {
        String url = "prod-api/api/takeout/category/list?sellerId="+rowsDTO.getId();
        OkHttpTool.doNetRequest(url, OkHttpTool.GET, CategoryData.class, new OkHttpTool.NetCallback() {
            @Override
            public void onSuccess(Object obj) {
                CategoryData categoryData = (CategoryData)obj;
                if(categoryData.getCode() == 200){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            category.setLayoutManager(new LinearLayoutManager(Details02Activity.this));
                            category.setAdapter(new CategroyAdapter(categoryData.getData(), Details02Activity.this, new CategroyAdapter.Callback() {
                                @Override
                                public void isReturn(String name) {

                                }
                            }));
                        }
                    });
                }
            }

            @Override
            public void onFailure(String msg) {

            }
        });

    }

    private void getTab() {
        listTab = new ArrayList<>();
        listTab.add("点菜");
        listTab.add("评价");
        listTab.add("商家介绍");
        for (String s : listTab) {
            TabLayout.Tab tab1 = tab.newTab();
            tab1.setText(s);
            tab.addTab(tab1);
        }
        tabCilak();
    }

    private void tabCilak() {
        tab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                if("点菜".equals(listTab.get(position))){
                    comment.setVisibility(View.GONE);
                    line1.setVisibility(View.VISIBLE);
                    line2.setVisibility(View.GONE);
                    getProduct();
                }else if("评价".equals(listTab.get(position))){
                    getComment();
                    comment.setVisibility(View.VISIBLE);
                    line1.setVisibility(View.GONE);
                    line2.setVisibility(View.GONE);
                }else if("商家介绍".equals(listTab.get(position))){
                    comment.setVisibility(View.GONE);
                    line1.setVisibility(View.GONE);
                    line2.setVisibility(View.VISIBLE);

                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void getComment() {
        String url ="prod-api/api/takeout/comment/list?sellerId="+rowsDTO.getId();
        OkHttpTool.doNetRequest(url, OkHttpTool.GET, CommentData.class, new OkHttpTool.NetCallback() {
            @Override
            public void onSuccess(Object obj) {
                CommentData commentData = (CommentData)obj;
                if(commentData.getCode() == 200){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            comment.setLayoutManager(new LinearLayoutManager(Details02Activity.this));
                            comment.setAdapter(new CommentAdapter(commentData.getRows(),Details02Activity.this));
                        }
                    });
                }
            }

            @Override
            public void onFailure(String msg) {

            }
        });
    }

    private void initExit() {
        exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Details02Activity.this.finish();
            }
        });
    }

    private void init() {

        line2 = findViewById(R.id.line2);
        imgUrl2 = findViewById(R.id.imgUrl2);
        name2 = findViewById(R.id.name2);
        address2 = findViewById(R.id.address2);
        settlement = findViewById(R.id.settlement);
        line1 = findViewById(R.id.line1);
        comment = findViewById(R.id.comment);
        exit = findViewById(R.id.exit);
        total_price = findViewById(R.id.total_price);
        product = findViewById(R.id.product);
        category = findViewById(R.id.category);
        name = findViewById(R.id.name);
        name1 = findViewById(R.id.name1);
        imgUrl = findViewById(R.id.imgUrl);
        score = findViewById(R.id.score);
        tab = findViewById(R.id.tab);
        saleQuantity = findViewById(R.id.saleQuantity);
        avgCost = findViewById(R.id.avgCost);
        intent = getIntent();
        String stringExtra = intent.getStringExtra(Common.COMMON);
        gson = new Gson();
        rowsDTO = gson.fromJson(stringExtra, NearData.RowsDTO.class);
        name1.setText(rowsDTO.getName());
        Glide.with(Details02Activity.this).load(OkHttpTool.URL + rowsDTO.getImgUrl()).into(imgUrl);
        score.setText(rowsDTO.getScore()+"分");
        saleQuantity.setText("销量:"+rowsDTO.getSaleQuantity());
        avgCost.setText("人均消费"+rowsDTO.getAvgCost());
        name.setText(rowsDTO.getName());
        jsonObject1 = new JSONObject();
        sc = findViewById(R.id.sc);
        comment.setVisibility(View.GONE);
        line1.setVisibility(View.VISIBLE);
        getProduct();
        Glide.with(Details02Activity.this).load(OkHttpTool.URL+rowsDTO.getImgUrl()).into(imgUrl2);
        name2.setText(rowsDTO.getName());
        address2.setText(rowsDTO.getAddress());
    }
}